package com.yyfax.ph.personal.authority;

import android.text.TextUtils;
import com.yyfax.common.CLog;
import com.yyfax.infrastructure.mvp.IView;
import com.yyfax.infrastructure.mvp.Model;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.network.NetworkHelper;
import com.yyfax.infrastructure.network.entity.BaseResultEntity;
import com.yyfax.infrastructure.network.entity.EmptyEntity;
import com.yyfax.ph.base.YJPH;
import com.yyfax.ph.common.GlobalVariableConfig;
import retrofit2.http.Body;
import retrofit2.http.Header;
import retrofit2.http.POST;
import rx.Observable;
import rx.Subscriber;


/**
 * 需要加密的页面的p需要继承此presenter
 */

public abstract class RSAPresenter<M extends Model, V extends IView> extends Presenter<M, V> {
	private static final String TAG = RSAPresenter.class.getSimpleName();

	@Override
	public void execute(final Object params, final int functionalCode, final boolean autoTips, final Object extraParam, final String requestPage) {
		if (!TextUtils.isEmpty(GlobalVariableConfig.getKeyRSA())) {
			RSAPresenter.super.execute(getRSAParams(params, functionalCode), functionalCode, autoTips, extraParam, requestPage);
		} else {
			mModel.execute(getRSAObservable(), new Subscriber() {
				@Override
				public void onStart() {
					RSAPresenter.super.onStart(true);
				}

				@Override
				public void onCompleted() {
					RSAPresenter.super.onCompleted(true);
				}

				@Override
				public void onError(Throwable e) {
					RSAPresenter.this.onError(e, true);
				}

				@Override
				public void onNext(Object o) {
					//加密
					RSAResult rsaResult = (RSAResult) o;
					if (isResponseSuccess(rsaResult) && null != rsaResult.getContent()) {
						GlobalVariableConfig.setKeyRSA(rsaResult.getContent());
						RSAPresenter.super.execute(getRSAParams(params, functionalCode), functionalCode, autoTips, extraParam, requestPage);
					} else {
						//todo 错误提示
						CLog.i(TAG, rsaResult.getMsg());
					}

				}
			}, FUNCTIONAL_CODE, null, null);
		}
	}

	public Observable getRSAObservable() {
		Service service = (Service) NetworkHelper.createService(Service.class);
		String token = YJPH.getInstance().getPreferenceManager().getLoginToken();
		return service.getRsa(token, new EmptyEntity());
	}

	private interface Service {
		@POST("sys/key/update")
		Observable<RSAResult> getRsa(@Header("token") String token, @Body EmptyEntity rsa);
	}

	static class RSAResult extends BaseResultEntity<String> {
	}

	/**
	 * 子类实现，对参数进行加密
	 */
	public abstract Object getRSAParams(Object params, int functionalCode);


}
